<template>
  <view class="login-page">

     <header class="header">
      <image class="header-image" src="/static/header-bg.png" mode="aspectFill"></image>
      
      <!-- 返回按钮 -->
      <view class="back-button" @click="goBack">
        <image class="back-icon" src="/static/back-icon.png" mode="aspectFit"></image>
      </view>
      
      <view class="hero-content">
        <!-- 左侧文本区域 -->
        <view class="hero-text">
          <text class="welcome">HI,欢迎新朋友~</text>
          <text class="slogan">好玩世界，尽在社交搭子</text>
        </view>
        
        <!-- 右侧图片区域 -->
        <view class="hero-image">
          <image src="/static/welcome-image.png" mode="aspectFit"></image>
        </view>
      </view>
    </header>

    <!-- 表单卡片 -->
    <view class="card">
      <view class="field">
        <text class="label">你的手机号</text>
        <input class="input" v-model="phone" type="number" placeholder="请输入手机号" maxlength="11" />
      </view>
      <view class="divider"></view>
      
      <!-- 验证码登录模式 -->
      <view class="field row" v-if="!isPasswordMode">
        <view class="col">
          <text class="label">验证码</text>
          <input class="input" v-model="code" type="number" placeholder="请输入验证码" maxlength="4" />
        </view>
        <button class="code-btn" :disabled="countdown>0" @click="onGetCode">
          {{ countdown>0 ? `${countdown}s` : '获取验证码' }}
        </button>
      </view>
      
      <!-- 密码登录模式 -->
      <view class="field" v-else>
        <text class="label">密码</text>
        <input class="input" v-model="password" type="password" placeholder="请输入密码" />
      </view>
    </view>

    <!-- 切换按钮和忘记密码 -->
    <view class="card-actions">
      <view class="left-action">
        <view class="switch-mode" @click="toggleLoginMode">
          <image class="icon" :src="isPasswordMode ? '/static/phone-icon.png' : '/static/password-icon.png'" />
                  {{ isPasswordMode ? '验证码登录' : '密码登录' }}
        </view>          
      </view>
      <view class="right-action">
        <view class="forgot-password" @click="onForgotPassword">
            <image class="icon" src="/static/forgot-password-icon.png" />
          忘记密码
        </view>
      </view>
    </view>

    <!-- 辅助登录方式 -->
    <view class="alt-login">
      <view class="alt-title">
        <view class="line"></view>
        <text>第三方登录</text>
        <view class="line"></view>
      </view>
      <view class="wechat-btn" @click="onWeChatLogin">
        <image class="wechat-icon" src="/static/wechat-icon.png" />
      </view>
    </view>

    <!-- 协议与按钮 -->
    <view class="agreement">
      <view class="checkbox" :class="{ checked: agreed }" @click="agreed = !agreed"></view>
      <text>我已阅读并同意</text>
      <text class="link" @click="onAgreementClick(1)">《用户服务协议》</text>
      <text>、</text>
      <text class="link" @click="onAgreementClick(2)">《隐私协议》</text>
    </view>

    <button class="login-btn" @click="onLogin">
      登录
    </button>

    <view class="register" @click="goRegister">注册</view>
  </view>
</template>

<script setup>
  import { ref } from 'vue';
  import sheep from '@/sheep';
  import { onLoad } from '@dcloudio/uni-app';
  import AuthUtil from '@/sheep/api/member/auth';

  const phone = ref('');
  const code = ref('');
  const password = ref('');
  const agreed = ref(false);
  const countdown = ref(0);

  // 返回首页
  const goBack = () => {
    const pages = getCurrentPages();
    if (pages.length > 1) {
      uni.navigateBack();
    } else {
      uni.switchTab({ url: '/pages/index/index' });
    }
  };
  const isPasswordMode = ref(true);
  let timer = null;

  // 切换登录模式
  const toggleLoginMode = () => {
    isPasswordMode.value = !isPasswordMode.value;
    // 清空输入框
    code.value = '';
    password.value = '';
  };

  const onGetCode = () => {
    if (countdown.value > 0) return;
    if (phone.value.length !== 11) {
      return uni.showToast({ title: '请输入正确手机号', icon: 'none' });
    }
    // 调用发送验证码接口，scene=1 表示登录场景
    AuthUtil.sendSmsCode(phone.value, 1)
      .then((res) => {
        if (!res || res.code !== 0) {
          console.warn('[Login] sendSmsCode failed', res);
          return Promise.reject(res);
        }
        countdown.value = 60;
        timer = setInterval(() => {
          countdown.value--;
          if (countdown.value <= 0) {
            clearInterval(timer);
            timer = null;
          }
        }, 1000);
      })
      .catch((error) => {
        console.error('发送验证码失败:', error);
      });
  };

  const onLogin = () => {
  // 验证手机号
  if (phone.value.length !== 11) {
    return uni.showToast({ title: '请输入正确手机号', icon: 'none' });
  }
  
  // 验证协议是否勾选
  if (!agreed.value) {
    return uni.showToast({ title: '请阅读并同意用户协议和隐私政策', icon: 'none' });
  }
  
  // 根据登录模式选择不同的登录方式
  if (isPasswordMode.value) {
    // 密码登录
    if (!password.value) {
      return uni.showToast({ title: '请输入密码', icon: 'none' });
    }
    
    // 使用手机 + 密码登录
    AuthUtil.login({ mobile: phone.value, password: password.value })
      .then(async (res) => {
        if (!res || res.code !== 0 || !res.data?.accessToken) {
          return Promise.reject(res);
        }
        // 等待 token 保存完成（响应拦截器会自动保存）
        await new Promise(resolve => setTimeout(resolve, 100));
        const token = uni.getStorageSync('token');
        if (!token) {
          uni.showToast({ title: '登录失败，token未保存', icon: 'none' });
          return;
        }
        // 等待 loginAfter 完成
        try {
          const userStore = sheep.$store('user');
          if (userStore && userStore.loginAfter) {
            await userStore.loginAfter();
          }
        } catch (error) {
          console.warn('loginAfter 执行失败:', error);
        }
        // 跳转
        let returnUrl = uni.getStorageSync('returnUrl');
        if (returnUrl) {
          uni.removeStorage({ key: 'returnUrl' });
          uni.redirectTo({ url: returnUrl });
        } else {
          uni.switchTab({ url: '/pages/index/index' });
        }
      })
      .catch((error) => {
        console.error('登录失败:', error);
        // 处理特定错误码
        if (error && error.code === 1002000000) {
          // 账号密码不正确的错误
          uni.showToast({ title: error.msg || '登录失败，账号密码不正确', icon: 'none' });
        } else {
          // 其他错误
          uni.showToast({ title: error?.msg || '登录失败，请重试', icon: 'none' });
        }
      });
  } else {
    // 验证码登录
    if (code.value.length !== 4) {
      return uni.showToast({ title: '请输入4位验证码', icon: 'none' });
    }
    
    // 使用手机 + 验证码登录
    AuthUtil.smsLogin({ mobile: phone.value, code: code.value })
      .then(async (res) => {
        if (!res || res.code !== 0 || !res.data?.accessToken) {
          return Promise.reject(res);
        }
        // 等待 token 保存完成（响应拦截器会自动保存）
        await new Promise(resolve => setTimeout(resolve, 100));
        const token = uni.getStorageSync('token');
        if (!token) {
          uni.showToast({ title: '登录失败，token未保存', icon: 'none' });
          return;
        }
        // 等待 loginAfter 完成
        try {
          const userStore = sheep.$store('user');
          if (userStore && userStore.loginAfter) {
            await userStore.loginAfter();
          }
        } catch (error) {
          console.warn('loginAfter 执行失败:', error);
        }
        // 跳转
        let returnUrl = uni.getStorageSync('returnUrl');
        if (returnUrl) {
          uni.removeStorage({ key: 'returnUrl' });
          uni.redirectTo({ url: returnUrl });
        } else {
          uni.switchTab({ url: '/pages/index/index' });
        }
      })
      .catch((error) => {
        console.error('登录失败:', error);
        // 处理特定错误码
        if (error && error.code === 1002000000) {
          // 账号或验证码错误
          uni.showToast({ title: error.msg || '登录失败，账号或验证码不正确', icon: 'none' });
        } else {
          // 其他错误
          uni.showToast({ title: error?.msg || '登录失败，请重试', icon: 'none' });
        }
      });
  }
};

  const onForgotPassword = () => {
    uni.navigateTo({ url: '/pages/index/forgot-password' });
  };

  const goRegister = () => {
    uni.navigateTo({ url: '/pages/index/register' });
  };

  const onWeChatLogin = () => {
    // 唤起平台微信登录
    try {
      sheep.$platform.useProvider().login();
    } catch (e) {
      uni.showToast({ title: '请在支持的平台使用微信登录', icon: 'none' });
    }
  };

  // 协议点击事件
  const onAgreementClick = (id) => {
    uni.navigateTo({ 
      url: `/pages/index/agreement?id=${id}`
    });
  };
  
  onLoad(async (options) => {
    // #ifdef H5
    // 仅当是微信等平台登陆回调（带 event 参数）时，才执行回调并跳转首页
    new URLSearchParams(location.search).forEach((value, key) => { options[key] = value; });
    const event = options?.event; const codeParam = options?.code; const state = options?.state;
    if (event === 'login') {
      await sheep.$platform.useProvider().login(codeParam, state);
    } else if (event === 'bind') {
      await sheep.$platform.useProvider().bind(codeParam, state);
    }
    if (event === 'login' || event === 'bind') {
      let returnUrl = uni.getStorageSync('returnUrl');
      if (returnUrl) { uni.removeStorage({ key: 'returnUrl' }); location.replace(returnUrl); } else { uni.switchTab({ url: '/' }); }
    }
    // #endif
  });
</script>

<style scoped>  
  .login-page {
    min-height: 100vh;
    background: #F6F6F6;
    padding: 0 0 40rpx 0;
  }
  .header {
    position: relative;
    height: 480rpx;
    width: 100%;
    margin-bottom: 0;
  }

  /* 返回按钮样式 */
  .back-button {
    position: absolute;
    left: 20rpx;
    top: 60rpx;
    width: 80rpx;
    height: 80rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 999;
    background: rgba(255, 255, 255, 0.2);
    border-radius: 50%;
    backdrop-filter: blur(10rpx);
  }

  .back-icon {
    width: 100rpx;
    height: 100rpx;
  }
  .header-image {
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    z-index: 1;
  }
  .hero-content {
    position: absolute;
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
    padding: 0rpx 50rpx;
    z-index: 20;
  }
  
  /* 左侧文本样式 */
  .hero-text {
    flex: 1;
    padding-right: 30rpx;
  }
  .welcome { 
    display: block; 
    font-size: 48rpx; 
    font-weight: 800; 
    color: #000000; 
    margin-bottom: 12rpx; 
    margin-top: -250rpx;
  }
  .slogan { 
    display: block; 
    font-size: 26rpx; 
    color: #666; 
  }
  .hero-image {
    width: 321rpx;
    height: 306rpx;
    margin-top: -300rpx;
    margin-right: 53rpx;
  }
  .hero-image image {
    width: 100%;
    height: 100%;
    border-radius: 24rpx;
  }
  .card { 
    background: #fff; 
    border-radius: 20rpx; 
    padding: 24rpx; 
    /* box-shadow: 0 8rpx 24rpx rgba(0,0,0,.06);  */
    margin-top: -40rpx; 
    margin-left: 17rpx; 
    margin-right: 17rpx;
    z-index: 30;
    position: relative;
  }
  .field {
    margin-top: 20rpx;
    margin-bottom: 8rpx; 
  }
  .row { 
    display: flex; 
    align-items: center; 
    gap: 16rpx; 
  }
  .col { 
    flex: 1; 
  }
  .label { 
    display: block; 
    font-size: 30rpx; 
    font-weight: 700; 
    color: #1f2937; 
    padding: 10rpx 20rpx;
  }
  .input { 
    width: 100%; 
    height: 80rpx; 
    border: 0; 
    background: transparent; 
    font-size: 28rpx; 
    color: #111; 
    padding: 0rpx 20rpx;
  }
  .input::placeholder {
    color: #c0c4cc; 
  }
  .divider { 
    height: 2rpx; 
    background: #f1f2f6; 
    margin: 8rpx 20rpx 20rpx 20rpx; 
  }
  .code-btn { 
    padding: 0 20rpx; 
    height: 72rpx; 
    line-height: 72rpx; 
    border-radius: 36rpx; 
    color: #fff; 
    font-size: 26rpx; 
    background: linear-gradient(90deg,#a78bfa,#60a5fa); 
    margin-right: 15rpx;
  }
  .code-btn[disabled] { 
    opacity: .5; 
  }

  .alt-login { margin: 48rpx 0 24rpx; display: flex; flex-direction: column; align-items: center; }
  .alt-title { 
    display: flex; 
    align-items: center; 
    gap: 24rpx; 
    color: #000000; 
    font-size: 26rpx; 
    margin-bottom: 20rpx; 
    margin-top: 100rpx;
  }
  .alt-title .line { 
    width: 80rpx; 
    height: 1rpx; 
    background: #787676; 
  }
  .wechat-btn { 
    display: flex; 
    align-items: center; 
    justify-content: center; 
    margin-top: 30rpx;
    margin-bottom: 30rpx;
  }
  .wechat-icon { 
    width: 100rpx; 
    height: 100rpx; 
  }

  .agreement { 
    display: flex; 
    justify-content: center;
    gap: 10rpx; color: #8a8f98; 
    font-size: 24rpx; 
    margin-top: 80rpx;
    margin-bottom: 40rpx;
  }
  .checkbox { 
    width: 34rpx; 
    height: 34rpx; 
    border-radius: 50%; 
    border: 2rpx solid #cbd5e1; background: #fff; 
    display: inline-flex; 
    align-items: center; 
    justify-content: center; 
  }
  .checkbox.checked { 
    background: linear-gradient(90deg,#a78bfa,#60a5fa); 
    border-color: transparent; 
  }
  .link { 
    color: #4f46e5; 
  }

  .login-btn { 
    width: 85%; 
    height: 80rpx; 
    line-height: 80rpx; 
    border-radius: 56rpx; 
    color: #fff; 
    font-size: 30rpx; 
    background: linear-gradient(90deg, #B276FF 0%, #74A7FF 100%); 
  }
  .register { 
    text-align: center; 
    color: #9aa1aa; 
    margin-top: 40rpx; 
    font-size: 26rpx; 
  }
  .card-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin: 20rpx 17rpx 0 17rpx;
  }
  
  .left-action {
    flex: 1;
    text-align: left;
  }
  
  .right-action {
    flex: 1;
    text-align: right;
  }

  .card-actions {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin: 20rpx 17rpx 0 17rpx;
  }
  
  .switch-mode {
    color: rgba(23, 26, 29, 0.4);
    font-size: 26rpx;
    cursor: pointer;
    display: inline-flex;
    align-items: center;
    gap: 8rpx;
    padding-left: 20rpx;
  }
  
  .forgot-password {
    color: #9aa1aa;
    font-size: 26rpx;
    cursor: pointer;
    display: inline-flex;
    align-items: center;
    gap: 8rpx;
    padding-right: 20rpx;
  }
  .icon {
    width: 24rpx;
    height: 24rpx;
  }
</style>